<template>
	<view class="container">
		<!-- 地图容器 -->
		<map id="myMap" style="width: 100%; height: 50vh;" :latitude="center.latitude" :longitude="center.longitude"
			:markers="markers" :polyline="polyline" :include-points="includePoints" show-location></map>

		<!-- 控制面板 -->
		<view class="control-panel">
			<button @click="startTracking" :disabled="isTracking">开始追踪</button>
			<button @click="stopTracking" :disabled="!isTracking">停止追踪</button>
			<button @click="replanRoute">重新规划路线</button>
		</view>

		<!-- 状态信息 -->
		<view class="status">
			<text>状态: {{ statusText }}</text>
			<text>当前位置: {{ formatPosition(currentPosition) }}</text>
			<text v-if="startPosition">起点: {{ startPosition.name || formatPosition(startPosition) }}</text>
			<text v-if="endPosition">终点: {{ endPosition.name || formatPosition(endPosition) }}</text>
			<text v-if="routeDistance">距离: {{ routeDistance }}</text>
			<text v-if="routeDuration">预计时间: {{ formatDuration(routeDuration) }}</text>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		computed,
		onMounted,
		onUnmounted
	} from 'vue'
	import {
		onLoad,
		onShow,
		onHide
	} from '@dcloudio/uni-app'
	import amap from '../amap-wx.130.js'

	// 状态变量
	const isTracking = ref(false)
	const statusText = ref('初始化中...')
	const currentPosition = ref({
		latitude: 0,
		longitude: 0
	})
	const startPosition = ref(null)
	const endPosition = ref(null)
	const center = ref({
		latitude: 39.9042,
		longitude: 116.4074
	}) // 默认北京中心点
	const markers = ref([])
	const polyline = ref([])
	const includePoints = ref([])
	const routeDistance = ref(0)
	const routeDuration = ref(0)
	let socketTask = null
	let locationUpdateInterval = null

	// 计算属性
	const canPlanRoute = computed(() => {
		return startPosition.value && endPosition.value
	})

	// 格式化位置显示
	const formatPosition = (pos) => {
		if (!pos) return '未设置'
		return `${pos.latitude.toFixed(6)}, ${pos.longitude.toFixed(6)}`
	}

	// 格式化时间显示
	const formatDuration = (seconds) => {
		if (seconds < 60) return `${seconds}秒`
		const mins = Math.floor(seconds / 60)
		const secs = seconds % 60
		return `${mins}分钟${secs > 0 ? `${secs}秒` : ''}`
	}

	// 初始化WebSocket连接
	const initWebSocket = () => {
		const wsUrl = 'ws://localhost:8080'
		// /ws/{id}/{ctype}/{no}/{area}

		socketTask = uni.connectSocket({
			url: wsUrl,
			success: () => console.log('WebSocket连接成功'),
			fail: (err) => console.error('WebSocket连接失败:', err)
		})

		socketTask.onOpen(() => console.log('WebSocket已打开'))
		socketTask.onError((err) => console.error('WebSocket错误:', err))
	}

	// 发送位置信息到服务器
	const sendLocationToServer = (location) => {
		if (socketTask && socketTask.readyState === 1) {
			const message = {
				type: 'location_update',
				data: {
					latitude: location.latitude,
					longitude: location.longitude,
					timestamp: new Date().getTime(),
					speed: location.speed || 0,
					accuracy: location.accuracy || 0,
					route: polyline.value.length > 0
				},
				// data:{
				// 	DeliveryNo:'',//派送订单号
				// 	SendType:2,// App请求类型,1司机、2客户
				// 	 MessageType:'',//1.司机：changeNO改单,completeNo完成订单,sendMsessage发送信息,close关闭;2.客户：sendMessage,changNo,close
				// 	 SendClentId:'',//用户id
				// 	 CEarthInfo:'',//起点位置
				// 	 EEarthInfo:'',//终点位置
				// 	 Msg:'' //消息
				// }
			}
			socketTask.send({
				data: JSON.stringify(message),
				success: () => console.log('位置信息发送成功'),
				fail: (err) => console.error('位置信息发送失败:', err)
			})
		}
	}

	// 获取当前位置
	const getCurrentLocation = async () => {
		try {
			const res = await uni.getLocation({
				type: 'gcj02',
				isHighAccuracy: true
			})
			updateCurrentPosition(res)
			return res
		} catch (err) {
			console.error('获取当前位置失败:', err)
			uni.showModal({
				title: '提示',
				content: '需要获取您的位置权限才能提供服务',
				showCancel: false,
				success() {
					wx.openSetting({
						success: (res) => {
							if (res.authSetting["scope.userLocation"]) { // 用户同意授权
								console.log("用户同意授权");
								getCurrentLocation();
							}
						}
					})
				}
			})
			throw err
		}
	}

	// 获取附近位置作为起点
	const getNearbyRestaurant = async (currentPos) => {
		try {
			// 这里模拟从服务器获取附近
			// 实际应用中应该调用后端API获取真实数据
			return {
				latitude: currentPos.latitude + 0.002,
				longitude: currentPos.longitude + 0.002,
				name: '模拟附近位置：起点',
				address: '模拟区测试路123号'
			}
		} catch (err) {
			console.error('获取附近位置失败:', err)
			throw err
		}
	}

	// 获取用户地址作为终点
	const getUserAddress = async () => {
		try {
			// 这里模拟从服务器获取用户地址
			// 实际应用中应该调用后端API获取真实数据
			const currentPos = await getCurrentLocation()
			return {
				latitude: currentPos.latitude - 0.005,
				longitude: currentPos.longitude - 0.005,
				name: '模拟用户地址：终点',
				address: '模拟区用户路456号'
			}
		} catch (err) {
			console.error('获取用户地址失败:', err)
			throw err
		}
	}

	// 开始追踪位置
	const startTracking = async () => {
		if (isTracking.value) return

		try {
			// 请求位置权限
			await uni.authorize({
				scope: 'scope.userLocation'
			})

			// 前台定位
			await uni.startLocationUpdate()
			console.log('前台定位开始')

			// 后台定位
			await uni.startLocationUpdateBackground()
			console.log('后台定位开始')

			isTracking.value = true
			statusText.value = '追踪中...'

			// 监听位置变化
			uni.onLocationChange((res) => {
				console.log('位置变化:', res)
				updateCurrentPosition(res)
				sendLocationToServer(res)
				saveToStorage()
			})

		} catch (err) {
			console.error('定位失败:', err)
			statusText.value = '定位失败'
			wx.getSetting({
				success(res){
					console.log(1, res.authSetting);
				}
			})
			uni.showModal({
				title: '提示',
				content: '需要获取您的位置权限才能提供服务!',
				showCancel: false,
				success() {
					// 小程序接口审核通过后再打开
					wx.openSetting({
						success: (res) => {
							console.log("位置权限",res);
							if (res.authSetting["scope.userLocation"]) { // 用户同意授权
								console.log("用户同意授权");
								startTracking();
							}
						}
					})
				}
			})


		}
	}

	// 更新当前位置
	const updateCurrentPosition = (res) => {
		currentPosition.value = {
			latitude: res.latitude,
			longitude: res.longitude,
			speed: res.speed,
			accuracy: res.accuracy
		}
		center.value = {
			...currentPosition.value
		}
		// 计算距离单位
		let distance = 0
		 const num = parseFloat(routeDistance.value);
		      if (isNaN(num)) distance = '0米';
		      
		      // 判断距离大小选择单位
		      if (num >= 1000) {
		        const km = num / 1000;
		        // 保留1位小数并去除多余的.0
		        let kmStr = km.toFixed(1).replace(/\.0$/, '');
		        distance = `${kmStr}公里`;
		      } else {
		        // 不满1公里直接显示米（原单位取整）
		        distance = `${Math.round(num)}米`;
		      }
			  
		// 更新骑手标记
		const riderMarker = {
			id: 1,
			latitude: res.latitude,
			longitude: res.longitude,
			iconPath: '/static/images/car.png',
			width: 30,
			height: 30,
			callout: {
				content: `司机距您${distance},预计还有${formatDuration(routeDuration.value)}送达`,
				color: '#ffffff',
				bgColor: '#007AFF',
				padding: 5,
				borderRadius: 4,
				display: 'ALWAYS'
			}
		}

		// 保留起点和终点标记
		markers.value = markers.value.filter(m => m.id !== 1)
		markers.value.unshift(riderMarker)
	}

	// 停止追踪位置
	const stopTracking = () => {
		if (!isTracking.value) return

		uni.stopLocationUpdate({
			success: () => {
				console.log('停止定位成功')
				isTracking.value = false
				statusText.value = '已停止追踪'
				uni.offLocationChange(() => {})
			},
			fail: (err) => console.error('停止定位失败:', err)
		})
	}

	// 更新标记点
	const updateMarkers = () => {
		// 清除旧的起点和终点标记
		markers.value = markers.value.filter(m => m.id === 1)

		// 添加起点标记
		if (startPosition.value) {
			markers.value.push({
				id: 2,
				latitude: startPosition.value.latitude,
				longitude: startPosition.value.longitude,
				iconPath: '/static/images/start.png',
				width: 30,
				height: 30,
				callout: {
					content: `起点: ${startPosition.value.name}`,
					color: '#ffffff',
					bgColor: '#4CD964',
					padding: 5,
					borderRadius: 4,
					display: 'ALWAYS'
				}
			})
		}

		// 添加终点标记
		if (endPosition.value) {
			markers.value.push({
				id: 3,
				latitude: endPosition.value.latitude,
				longitude: endPosition.value.longitude,
				iconPath: '/static/images/end.png',
				width: 30,
				height: 30,
				callout: {
					content: `终点: ${endPosition.value.name}`,
					color: '#ffffff',
					bgColor: '#FF2D55',
					padding: 5,
					borderRadius: 4,
					display: 'ALWAYS'
				}
			})
		}

		// 更新地图显示范围
		updateIncludePoints()
	}

	// 更新地图显示范围
	const updateIncludePoints = () => {
		const points = []

		if (currentPosition.value.latitude) {
			points.push({
				...currentPosition.value
			})
		}

		if (startPosition.value) {
			points.push({
				...startPosition.value
			})
		}

		if (endPosition.value) {
			points.push({
				...endPosition.value
			})
		}

		includePoints.value = points
	}

	// 规划路线
	const planRoute = async () => {
		if (!canPlanRoute.value) {
			uni.showToast({
				title: '缺少起点或终点',
				icon: 'none'
			})
			return
		}

		uni.showLoading({
			title: '路线规划中...',
			mask: true
		})

		try {
			// const res = await uni.request({
			//   url: 'https://restapi.amap.com/v3/direction/driving',
			//   data: {
			//     key: '2e4db96d15617dbd7e96e58b86463ab2',
			//     origin: `${startPosition.value.longitude},${startPosition.value.latitude}`,
			//     destination: `${endPosition.value.longitude},${endPosition.value.latitude}`,
			//     strategy: 10, // 10表示速度优先
			//     extensions: 'all' // 返回所有信息
			//   }
			// })

			// console.log("res 路线规划",res);
			// if (res.data.status === '1' && res.data.route?.paths[0]) {
			//   const path = res.data.route.paths[0]
			//   const steps = path.steps || []
			//   const points = []

			//   // 解析路线点
			//   steps.forEach(step => {
			//     const polylineStr = step.polyline
			//     polylineStr.split(';').forEach(point => {
			//       const [longitude, latitude] = point.split(',')
			//       points.push({
			//         latitude: parseFloat(latitude),
			//         longitude: parseFloat(longitude)
			//       })
			//     })
			//   })

			//   // 更新路线
			//   polyline.value = [{
			//     points: points,
			//     color: '#0091FF',
			//     width: 6,
			//     dottedLine: false,
			//     arrowLine: true
			//   }]

			//   // 更新距离和时间
			//   routeDistance.value = path.distance
			//   routeDuration.value = path.duration

			//   // 更新地图显示范围
			//   updateIncludePoints()

			//   statusText.value = '路线规划完成'
			//   saveToStorage()

			//   // 自动开始追踪
			//   startTracking()
			// } else {
			//   throw new Error(res.data.info || '路线规划失败')
			// }
			var myAmapFun = new amap.AMapWX({
				key: '2e4db96d15617dbd7e96e58b86463ab2'
			});
			myAmapFun.getDrivingRoute({
				origin: `${startPosition.value.longitude},${startPosition.value.latitude}`,
				destination: `${endPosition.value.longitude},${endPosition.value.latitude}`,
				success: function(data) {
					var points = [];
					if (data.paths && data.paths[0] && data.paths[0].steps) {
						var steps = data.paths[0].steps;
						for (var i = 0; i < steps.length; i++) {
							var poLen = steps[i].polyline.split(';');
							for (var j = 0; j < poLen.length; j++) {
								points.push({
									longitude: parseFloat(poLen[j].split(',')[0]),
									latitude: parseFloat(poLen[j].split(',')[1])
								})
							}
						}
					}
					// 更新路线
					polyline.value = [{
						points: points,
						color: "#0091ff",
						width: 6,
						dottedLine: false,
						arrowLine: true
					}]
					console.log("data 路线规划", data);
					// 更新距离和时间
					if (data.paths[0] && data.paths[0].distance) {
						routeDistance.value = data.paths[0].distance
						routeDuration.value = data.paths[0].duration
					}
					// 更新地图显示范围
					updateIncludePoints()
					statusText.value = '路线规划完成'
					saveToStorage()

					// 自动开始追踪
					startTracking()
				},
				fail: function(info) {

				}
			})
		} catch (err) {
			console.error('路线规划失败:', err)
			uni.showToast({
				title: err.message || '路线规划失败',
				icon: 'none'
			})
			statusText.value = '路线规划失败'
		} finally {
			uni.hideLoading()
		}
	}

	// 重新规划路线
	const replanRoute = async () => {
		await initPositions()
		await planRoute()
	}

	// 保存数据到本地存储
	const saveToStorage = () => {
		try {
			uni.setStorageSync('riderTrackingData', {
				currentPosition: currentPosition.value,
				startPosition: startPosition.value,
				endPosition: endPosition.value,
				polyline: polyline.value,
				routeDistance: routeDistance.value,
				routeDuration: routeDuration.value,
				isTracking: isTracking.value,
				lastUpdate: new Date().getTime()
			})
		} catch (err) {
			console.error('保存数据失败:', err)
		}
	}

	// 从本地存储加载数据
	const loadFromStorage = () => {
		try {
			const data = uni.getStorageSync('riderTrackingData')
			if (data) {
				// 检查数据是否过期（超过5分钟）
				const isExpired = new Date().getTime() - data.lastUpdate > 5 * 60 * 1000
				console.log("isExpired",isExpired);
				if (!isExpired) {
					currentPosition.value = data.currentPosition || currentPosition.value
					startPosition.value = data.startPosition || startPosition.value
					endPosition.value = data.endPosition || endPosition.value
					polyline.value = data.polyline || polyline.value
					routeDistance.value = data.routeDistance || routeDistance.value
					routeDuration.value = data.routeDuration || routeDuration.value

					if (data.currentPosition) {
						center.value = {
							...data.currentPosition
						}
					}
	// 更新标记点
					updateMarkers()
					// 更新地图显示范围
					updateIncludePoints()

					if (data.isTracking) {
						// 开始追踪位置
						startTracking()
					}

					return true
				}
			}
		} catch (err) {
			console.error('加载数据失败:', err)
		}
		return false
	}

	// 初始化位置信息
	const initPositions = async () => {
		try {
			statusText.value = '获取位置信息中...'

			// 获取当前位置
			const currentPos = await getCurrentLocation()

			// 获取起点（附近位置）
			startPosition.value = await getNearbyRestaurant(currentPos)

			// 获取终点（用户地址）
			endPosition.value = await getUserAddress()

			// 更新标记
			updateMarkers()

			statusText.value = '位置信息获取完成'
		} catch (err) {
			console.error('初始化位置失败:', err)
			statusText.value = '初始化失败'
		}
	}

	// 页面加载时初始化
	onLoad(async () => {
		// 连接websocket
		initWebSocket()
		// 规划路线
		// replanRoute()

		// 尝试从本地存储加载数据
		const hasData = loadFromStorage()

		if (!hasData) {
			// 如果没有保存的数据，则初始化新的路线
			await initPositions()
			await planRoute()
		}
	})

	// 页面显示时恢复追踪
	onShow(() => {
		if (isTracking.value) {
			startTracking()
		}
	})

	// 页面隐藏时停止追踪
	onHide(() => {
		stopTracking()
	})

	// 页面卸载时清理
	onUnmounted(() => {
		stopTracking()
		if (socketTask) {
			socketTask.close()
		}
	})
</script>

<style scoped>
	.container {
		display: flex;
		flex-direction: column;
		height: 60vh;
	}

	.control-panel {
		display: flex;
		flex-wrap: wrap;
		justify-content: space-around;
		padding: 10px;
		gap: 8px;
	}

	button {
		padding: 8px 12px;
		background-color: #007AFF;
		color: white;
		border: none;
		border-radius: 5px;
		font-size: 14px;
		flex: 1 1 30%;
		min-width: 100px;
	}

	button:disabled {
		background-color: #cccccc;
	}

	.status {
		padding: 10px;
		background-color: #f5f5f5;
		font-size: 12px;
		display: flex;
		flex-direction: column;
		gap: 4px;
	}
</style>